# @file    : image_analyse
# @time    : 2025/4/14
# @author  : yongpeng.yao
# @desc    :
import json
import os
from pathlib import Path

import oss2
from dotenv import load_dotenv
from openai import OpenAI

# 加载环境变量
load_dotenv()


def image_analyse(url):
    client = OpenAI(
        # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    )
    completion = client.chat.completions.create(
        model="qwen-vl-plus",
        messages=[{"role": "user", "content": [
            {"type": "text", "text": "请详细描述这张图片的内容、风格和重要元素。"
                                     "然后基于图片内容生成一段适合插入专业报告的文字描述(约100-150字)。"
                                     "直接返回生成的描述文本，不要添加其他解释。"},
            {"type": "image_url",
             "image_url": {"url": url}}
        ]}]
    )
    return json.loads(completion.model_dump_json())["choices"][0]['message']['content']


def image_upload_oss2(image_path):
    # 阿里云OSS的AccessKey信息
    access_key_id = 'LTAI5tMEgG3cHs9ziCkQGDoE'
    access_key_secret = 'PUdnpOAUKR5xnziQ9QKA8xIfBtI8ba'
    endpoint = 'https://oss-cn-chengdu.aliyuncs.com'
    bucket_name = 'image-test-moxiao'

    # 初始化OSS Bucket
    auth = oss2.Auth(access_key_id, access_key_secret)
    bucket = oss2.Bucket(auth, endpoint, bucket_name)

    # 上传图片
    file_name = Path(image_path).name
    object_name = f'image/{file_name}'  # 图片在OSS中的路径
    if bucket.object_exists(object_name):
        print(f"Object {object_name} already exists in bucket {bucket_name}.")
    else:
        with open(image_path, 'rb') as file_obj:
            bucket.put_object(object_name, file_obj)

    # 获取图片的URL
    image_url = get_public_url(bucket_name, endpoint, object_name)
    return image_url


def get_public_url(bucket_name, endpoint, object_name):
    # 处理endpoint格式
    if endpoint.startswith('https://'):
        base_url = endpoint.replace('https://', f'https://{bucket_name}.')
    else:
        base_url = f'https://{bucket_name}.{endpoint}'

    return f"{base_url}/{object_name}"


def image_analyse_to_text(image_path):
    image_url = image_upload_oss2(image_path)
    return image_analyse(image_url)


if __name__ == '__main__':
    image_url1 = image_upload_oss2("./image/lc3.png")
    print(image_url1)
    print(image_analyse(image_url1))
